package Servlet;

import DAO.BillDAO;
import DAO.CustomerDAO;
import DAO.DAOFactory;
import DAO.OrderDAO;
import javabean.Bill;
import javabean.Customer;
import javabean.Order;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/OrderRefund")
public class OrderRefundServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("UTF-8");
        int orderID = Integer.parseInt(req.getParameter("orderID"));
        CustomerDAO customerDAO = (CustomerDAO) DAOFactory.getCustomerDAOInstance();
        OrderDAO orderDAO = (OrderDAO) DAOFactory.getOrderDAOInstance();
        BillDAO billDAO = (BillDAO) DAOFactory.getBillDAOInstance();
        PrintWriter out = resp.getWriter();
        resp.setContentType("text/html;charset=utf-8");
        try {
            Order order = orderDAO.getOrderByID(orderID);
            Customer customer = customerDAO.searchCustomer(order.getCustomerID());
            if (customerDAO.recharge(customer, order.getPrice())) {
                Bill bill = new Bill();
                bill.setCreatedDate(new java.util.Date());
                bill.setCustomerID(customer.getCustomerID());
                bill.setPrice(order.getPrice());
                bill.setPaymentMethod("退款");
                bill.setModifiedDate(new java.sql.Timestamp(new java.util.Date().getTime()));
                bill.setPrice(order.getPrice());
                billDAO.balanceChange(bill);
                orderDAO.deleteOrder(order);
                out.print("<script>alert('退款成功!'); window.location='OrderManager' </script>");
            } else {
                out.print("<script>alert('退款失败!'); window.location='OrderManager' </script>");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
